var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var ueditor = require('ueditor');

var routes = require('./routes/index');
var users = require('./routes/users');
var util = require('./routes/util');
var topics = require('./routes/topics');

//加载时间差计算函数
var countTimeAgo = require('./config/countTimeAgo');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//配置网站图标
app.use(favicon(path.join(__dirname,'public','favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));


//使用cookies
app.use(cookieParser());

//将资源托管给public
app.use(express.static(path.join(__dirname, 'public')));

//将资源托管给uploads
app.use(express.static(path.join(__dirname, 'uploads')));

/*
  这样并不会冲突, 当在public路径下找不到资源, 则会去uploads目录下找 

*/

//定义session
app.use(session({
  secret:'stringUsedToEncrypt',
  resave:true,
  rolling:true,
  saveUninitialized:false,
  cookie:{
    maxAge: 1000*60*10080
  }
}));
//将session相关信息存储到本地对象中
app.use(function name(req,res,next) {
    //将session中的用户信息给本地用户对象
    res.locals.user = req.session.user;
    res.locals.err = req.session.errMsg;
    //将时间差计算方法挂载到全局对象中
    res.locals.countTimeAgo = countTimeAgo;
    next();
});

//配置存储一次性信息
app.use(flash());
//定义中间件捕获flash()携带的信息
app.use(function (req,res,next) {
  //next负责移交权限
  //console.log(req.flash('errMsg'));
  //继续向下执行
  //将错误信息赋值给全局对象
  res.locals.errMsg = req.flash('errMsg');
  //console.log(res.locals.errMsg);
  next();
});

//路由设置
app.use('/', routes);
//用户相关路由
app.use('/users', users);
//通用功能路由
app.use('/util', util);
//话题路由
app.use('/topics', topics);

// /ueditor 入口地址配置 https://github.com/netpi/ueditor/blob/master/example/public/ueditor/ueditor.config.js
// 官方例子是这样的 serverUrl: URL + "php/controller.php"
// 我们要把它改成 serverUrl: URL + 'ue'
app.use("/js/ueditor/ue", ueditor(path.join(__dirname, 'public'), function(req, res, next) {

  // ueditor 客户发起上传图片请求

  if(req.query.action === 'uploadimage'){

    // 这里你可以获得上传图片的信息
    var foo = req.ueditor;
    //console.log(foo.filename); // exp.png
    //console.log(foo.encoding); // 7bit
    //console.log(foo.mimetype); // image/png

    // 下面填写你要把图片保存到的路径 （ 以 path.join(__dirname, 'public') 作为根路径）
    var img_url = '/upload/image';
    res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做

  }else if (req.query.action === 'listimage'){//  客户端发起图片列表请求
    var dir_url = "/upload/image"; // 要展示给客户端的文件夹路径
    res.ue_list(dir_url) // 客户端会列出 dir_url 目录下的所有图片

  }else {// 客户端发起其它请求
    res.setHeader('Content-Type', 'application/json');
    // 这里填写 ueditor.config.json 这个文件的路径
    res.redirect('/js/ueditor/nodejs/config.json');
  }
}));



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
